package com.example.swaggerDemo.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.example.swaggerDemo.entity.MsgEntity;
import com.example.swaggerDemo.entity.SysUserEntity;
import com.example.swaggerDemo.service.UserService;
import com.example.swaggerDemo.util.EmojiUtils;
import com.example.swaggerDemo.util.MyHttpUtils;
import com.example.swaggerDemo.util.SessionUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.net.ssl.HttpsURLConnection;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;


@Api("微信登陆接口")
@RestController
@RequestMapping("/wxlogin")
public class LoginController {
    @Autowired
    private Environment env;
    @Autowired
    private UserService SysUserDao;
    private final Logger log = Logger.getLogger(this.getClass());

    @ApiOperation(value="微信登陆",notes="微信登陆")
    @RequestMapping(value="/wxloginurl",method= RequestMethod.POST)
    public void wxLogin(HttpServletResponse response) throws IOException {
        //请求获取code的回调地址
        //用线上环境的域名或者用内网穿透，不能用ip
        String callBack = env.getProperty("wxlogin.callback");
        System.out.println("进入微信登录");
        //请求地址
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize" +
                "?appid=" + env.getProperty("wxopen.appid") +
                "&redirect_uri=" + URLEncoder.encode(callBack, "UTF-8") +
                "&response_type=code" +
                "&scope=snsapi_userinfo" +
                "&state=STATE#wechat_redirect";
        response.sendRedirect(url);
    }


    @ApiOperation(value="微信登陆",notes="微信登陆")
    @ResponseBody
    @RequestMapping(value="/login",method= RequestMethod.GET)
    public void wxCallBack(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取access_token
        String code = request.getParameter("code");
        SysUserEntity dto=null;
        Object user=null;
        MsgEntity msg=new MsgEntity();
        log.info("回调方法....获取用户信息注册");
        log.info(code);
        String  avatar="";
         System.out.println("没有user:"+user);
        log.info(env.getProperty("wxopen.appid"));
        log.info(env.getProperty("wxpay.appsecret"));
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                "?appid=" + env.getProperty("wxlog.appid") +
                "&secret=" + env.getProperty("wxlog.appsecret") +
                "&code=" + code +
                "&grant_type=authorization_code";
        log.info(url);
        String result =  MyHttpUtils.doPost(url, "", Charset.forName("UTF-8").toString());

        System.out.println("请求获取access_token:" + result);
        //返回结果的json对象
        JSONObject resultObject = JSON.parseObject(result);

        SessionUtil.setSessionAttribute("OAuthAccessTokenStartTime", new Date());
        SessionUtil.setSessionAttribute("OAuthAccessToken", resultObject.getString("access_token"));
        //请求获取userInfo
        String infoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                "?access_token=" + resultObject.getString("access_token") +
                "&openid=" + resultObject.getString("openid") +
                "&lang=zh_CN";
        String resultInfo = MyHttpUtils.doPost(infoUrl, "", Charset.forName("UTF-8").toString());
        JSONObject userMessageJsonObject = JSON.parseObject(resultInfo);
        System.out.println(userMessageJsonObject);

        if (userMessageJsonObject != null) {
            try {

                //此时已获取到userInfo，再根据业务进行处理
                System.out.println("请求获取userInfo:" + userMessageJsonObject);
                //用户昵称
                String username = userMessageJsonObject.getString("nickname");
                username = EmojiUtils.emojiChange(username);
                //进行解码
                System.out.println("username"+username);
                String nickname = userMessageJsonObject.getString("nickname");
                System.out.println("nickname"+nickname);
                Object upopenid= SessionUtil.getSessionAttribute("upopenid");
                String level = "1";
                log.info(username+" "+ nickname+"upopenid"+upopenid);
                System.out.println(username+" "+ nickname+"upopenid"+upopenid);
                if (upopenid!=null&&upopenid!="")
                {
                    level = "0";
                }
                else {
                     level = "0";
                    upopenid="1636";//默认上级经纪人o62Y_wcACt6pn3v2h_-usI8s8J4A
                }
                Integer prevtime= Math.toIntExact(System.currentTimeMillis() / 1000);
                Integer jointime= Math.toIntExact(System.currentTimeMillis() / 1000);
                Integer logintime= Math.toIntExact(System.currentTimeMillis() / 1000);
                Integer createtime= Math.toIntExact(System.currentTimeMillis() / 1000);
                Integer updatetime= Math.toIntExact(System.currentTimeMillis() / 1000);

                //用户唯一标识
                String openid = userMessageJsonObject.getString("openid");
                System.out.println("openid"+openid);
                String city = userMessageJsonObject.getString("city");
                System.out.println("city"+city);
                String province = userMessageJsonObject.getString("province");
                System.out.println("province"+province);
                String avatar0 = userMessageJsonObject.getString("headimgurl");
                System.out.println("headimgurl"+avatar);
                String status="1";
                dto=  SysUserDao.findByOpenid(openid);
                if (dto!=null){
                    Integer s =getDistanceTime (createtime,dto.getUpdatetime());
                    System.out.println("已经差距"+s+"天");
                    if (s>30) {
                        avatar = env.getProperty("upload.url") + avatarUrl(avatar0);
                        if (avatar == "") {
                            avatar = avatar0;
                        }
                        SysUserDao.updatetoux(avatar,dto.getId().toString());
                    }
                    SysUserDao.updatehonmetime(dto.getMaxsuccessions()+1,dto.getId().toString());
                    if (upopenid!=""&&(dto.getUpopenid()==""||dto.getUpopenid()==null))
                    {
                        int a= SysUserDao.updateUpopenid(upopenid.toString(),dto.getId());
                        if(a>0){
                            System.out.println("修改用户upopenid成功:");
                            int c=  SysUserDao.updateTypedata("0",dto.getId().toString());
                            if(c>0){
                                msg.setcode(true);
                                System.out.println("修改用户类型为0成功:");
                                log.info("修改用户类型为0成功");
                            }
                            else
                            {
                                System.out.println("修改用户类型为0失败:");
                                msg.setmsg("修改用户类型为0失败:");
                                log.info("修改用户类型为0失败");
                            }
                        }
                        else
                        {
                            msg.setmsg("修改用户upopenid失败:");
                            System.out.println("修改用户upopenid失败:");
                        }

                    }
                }
                else {
                    avatar = env.getProperty("upload.url") + avatarUrl(avatar0);
                    if(avatar=="") {
                        avatar=avatar0;
                    }
                    if (openid != null) {
                        System.out.println("注册用户");
                        int k = SysUserDao.insert(username, nickname, "", avatar, level, prevtime, logintime, jointime, createtime, updatetime, status, openid, "0", "0", province + city, upopenid.toString());
                        if (k > 0) {
                            msg.setcode(true);
                            dto = SysUserDao.findByOpenid(openid);
                        } else {
                            msg.setmsg("注册用户信息失败！");
                            log.info("注册用户信息失败");
                            msg.setcode(false);
                        }
                    } else {
                        msg.setmsg("注册用户信息失败！你没有通过上级经纪人链接进入..");
                        msg.setcode(false);
                    }
                }
            } catch (JSONException e) {
                msg.setmsg("获取用户信息失败！");
                msg.setcode(false);
                log.info(e.getMessage());
            } catch (SQLException e) {
                log.info(e.getMessage());log.info(e.getMessage());
            }
        }
        SessionUtil.setSessionAttribute("loginUser", dto.getId()); // 设置 Session 中的

               msg.setobject(dto);
    response.sendRedirect(env.getProperty("wxlogin.callbackadlist")+"?userid="+dto.getId());
    }

    public  String avatarUrl(String imageUrl) throws IOException {
        String filePath =env.getProperty("upload.filePath");
        UUID uuid = UUID.randomUUID();
        filePath=filePath+uuid+".png";
        try {
            BufferedImage bufferedImage = ImageIO.read(new URL(imageUrl));
            File file = new File(filePath);
            ImageIO.write(bufferedImage,"jpg",file);
        }
        catch (Exception ex)
        {
            return "";
        }
        return  "/upload/" + uuid+".png";
    }

    public static int getDistanceTime(long time1, long time2) {
        long day = 0;
        long hour = 0;
        long min = 0;
        long sec = 0;
        long diff;

        if (time1 < time2) {
            diff = time2 - time1;
        } else {
            diff = time1 - time2;
        }
        day = diff / (24 * 60 * 60);
        hour = (diff / (60 * 60 * 1000) - day * 24);
        min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
        sec = (diff / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
        return Integer.parseInt(day+"")  ;
    }



}
